<template>
	<rui-pages>
		<rui-scan></rui-scan>
		<rui-layer ref="refLayer" @cancel="search" @change="change"></rui-layer>
	</rui-pages>
</template>

<script setup>
	import {
		ref
	} from "vue"

	import {
		onLoad,
		onHide
	} from "@dcloudio/uni-app"
	import {
		getBluetoothName,
		getBluetoothBind,
	} from "@/common/api.js"
	import cache from "@/util/cache"

	import Bluetooth from "@/util/bluetooth.js"
	const bluetooth = new Bluetooth();

	let refLayer = ref()
	let devices_list = [];
	let interval = ""

	onLoad(opts => {
		getBluetoothName().then(res => {
			devices_list = res.data;
			search()
		})
	})
	

	const change = e => {
		cache.put("DevicesInfo", e, 60 * 30)
		uni.$rui.route('/pages/bluetooth/add/add')
		stop();
	}
	
	const stop = () => {
		bluetooth.stop();
		clearInterval(interval)
	}
	const search = () => {
		console.log('开始获取设备')
		bluetooth.start(true)
		interval = setInterval(() => {
			getBle();
		}, 5000)
	}

	const getBle = () => {
		bluetooth.getBle(devices => {
			for (let key in devices) {
				let name = devices[key].name;
				let deviceId = devices[key].deviceId;

				if (name && name.search('不支持的设备') === -1) {
					if (devices_list.includes(name)) {
						getBluetoothBind({
							mac: deviceId,
							name
						}).then(res => {
							let dd = res.data;
							dd.mac = deviceId
							refLayer.value.open(dd)
							stop();
						})
					}
				}


			}
		})
	}
</script>

<style lang="scss" scoped>

</style>